package logs;

import com.sun.org.glassfish.gmbal.Description;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.apache.commons.codec.binary.Base64;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.HashMap;
import java.util.Map;

import static io.restassured.RestAssured.given;


public class login {
    static String code;
    static String clientId;
    static String clientSecret;
    
    @Test
    @Description("获取code")
        void getCode(){
        Response response = given()
                .when()
                .contentType("application/x-www-form-urlencoded")
                .param("responseType","code")
                .param("clientId","sevQNzgJSewmN6y")
                .param("userId","724413")
                .post("http://backend.comm.sit.wingconn.com/authorizationService/code")
                .then()
                .extract().response();
        System.out.println(response.asString());

        code = response.path("response.code");
        System.out.println(code);
        //获取响应信息中的状态码
        int satusCode = response.getStatusCode();
        Assert.assertEquals(satusCode,200,"获取code接口正常响应");
    }

    @Test
    @Description("根据code获取token")
        void getToken(){

        clientId = "sevQNzgJSewmN6y";
        clientSecret = "kWZr8ZEysKX86Tc";
        String authorization = encode(clientId+":"+clientSecret);

        //构造一个Map对象，用来请求头
        Map<String, String> headers = new HashMap<String,String>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("authorization", "Basic " + authorization);

        //构造一个Map对象，用来存多个参数
        Map<String, String> params = new HashMap<String,String>();
        params.put("grantType", "authorization_code");
        params.put("code", code);
        Response response = RestAssured.given()// 获取HttpRequest 请求对象
                .when()
                .headers(headers)
                .params(params)
                .post("http://backend.comm.sit.wingconn.com/authorizationService/token")// 获取HTTP服务器响应信息
                .then()
                .extract().response();

        //获取响应信息中的状态码
        int satusCode = response.getStatusCode();
        Assert.assertEquals(satusCode,200,"获取token接口正常响应");

        System.out.println(response.asString());//获取想要结果
        System.out.println(response.getStatusCode());//获取状态吗
        System.out.println(response.path("response.accessToken"));//获取token值

//       response System.out.println(response.extract());
    }



    public static String encode(String str) {//对字符串进行base64编码

        String asB64 = null;
        try {
            if (str == null) {
                return null;
            }
            asB64 = new String(Base64.encodeBase64(str.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return asB64;
    }

}
